package org.xserver.component.handler.ext.http;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.FileRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xserver.component.core.XServerHttpContextAttachment;
import org.xserver.component.core.XServerHttpResponse;
import org.xserver.component.core.http.HttpEnum;
import org.xserver.component.handler.ext.http.HttpResponseWriterHandlerFactory.HttpResponseType;

@Component
public class FileHttpResponseWriteHandler extends HttpResponseWriteHandler {

	private static final Logger logger = LoggerFactory
			.getLogger(FileHttpResponseWriteHandler.class);

	@Override
	public Object doGetContent(XServerHttpContextAttachment attachment,
			Object obj) {
		FileRegion fileRegion = (FileRegion) obj;

		// SimpleDateFormat dateFormatter = new
		// SimpleDateFormat(HTTP_DATE_FORMAT, Locale.CHINA);
		// dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

		// Date header
		// Calendar time = new GregorianCalendar();
		// response.headers().set(DATE, dateFormatter.format(time.getTime()));

		// Add cache headers
		// time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
		// response.headers().set(EXPIRES,
		// dateFormatter.format(time.getTime()));
		// response.headers().set(CACHE_CONTROL, "private, max-age=" +
		// HTTP_CACHE_SECONDS);

		logger.info("Response for Request [{}] is {}", attachment.getRequest()
				.getUri(), fileRegion.getCount());
		return obj;
	}

	@Override
	protected String getContentType(XServerHttpContextAttachment attachment,
			Object obj) {
		return HttpEnum.ContentType.APPLICATION_OCTET_STREAM.getContentType()
				+ "; " + XServerHttpResponse.DEFAULT_CHARSET;
	}

	@Override
	protected ChannelFutureListener getListener(
			final XServerHttpContextAttachment attachment, final Object obj)
			throws Exception {
		return new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture future)
					throws Exception {
				((FileRegion) obj).releaseExternalResources();
				attachment.operationComplete(future);

			}
		};
	}

	@Override
	protected ChannelFuture doWrite(XServerHttpContextAttachment attachment,
			Object obj) {
		Channel channel = attachment.getChannelHandlerContext().getChannel();
		channel.write(attachment.getResponse());
		return channel.write(obj);
	}

	@Override
	public String getResponseType(XServerHttpContextAttachment attachment) {
		return HttpResponseType.FILE.getType();
	}
}
